package com.nowoe.core.processor;

import com.nowoe.core.annotation.Resource;
import com.nowoe.core.bean.BeanFactory;
import com.nowoe.core.bean.BeanPostProcessor;
import com.nowoe.core.exception.InjectException;
import com.nowoe.core.proxy.TargetProxy;

import java.lang.reflect.Field;

/**
 * @author 倚栏听风 2023/9/16 11:12
 */
public class ResourceBeanPostProcessor implements BeanPostProcessor {
    @Override
    public void enhance(BeanFactory beanFactory, Object object) {
        if (object instanceof TargetProxy) {
            TargetProxy proxy = (TargetProxy) object;
            object = proxy.target();//获得原始类型
        }
        Field[] fields = object.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(Resource.class)) {
                Class<?> fieldType = field.getType();
                Object o = beanFactory.getBean(fieldType);
                if (o != null) {
                    field.setAccessible(true);
                    try {
                        field.set(object, o);
                    } catch (IllegalAccessException e) {
                        throw new InjectException("属性注入失败：" + object + "#" + field);
                    }
                } else {
                    throw new InjectException("属性注入失败（容器中无此对象）：" + object + "#" + field);
                }
            }
        }
    }
}
